package com.hc.java.conc;

import java.util.concurrent.Semaphore;

/**
 * @author cdhuangchao3
 * @date 2023/12/3 8:54 PM
 */
public class SemaphoreCase {
    public static void main(String[] args) {
        // 1.创建semaphore对象
        Semaphore semaphore = new Semaphore(3);
        // 2.10个线程同时运行
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    System.out.println("进入线程");
                    // 3.获取许可，计数-1
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    System.out.println("runing...");
                    Thread.sleep(1000);
                    System.out.println("end...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 4.释放许可 计数+1
                    semaphore.release();
                }
            }).start();
        }
    }
}
